// pages/login/login.js
var utils = require('../../utils/util')
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        info: {},
        code: '',
        isShow: false,
        canIUse: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        let that = this;
        that.setData({
            code: app.globalData.code
        });
        that.wxLogin();
        // wx.getSetting({
        //     withCredentials: true,
        //     success (res){
        //         if (res.authSetting['scope.userInfo']) {
        //             // 已经授权，可以直接调用 getUserInfo 获取头像昵称
        //             wx.getUserInfo({
        //                 success: function(res) {
        //                     console.log(res)
        //                 }
        //             });
        //             that.wxLogin();
        //         } else {
        //             that.setData({
        //                 canIUse: true
        //             });
        //         }
        //     }
        // });
    },
    wxLogin: function () {
        let that = this;
        wx.showLoading({
            title: '加载中'
        });
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                wx.hideLoading();
                if (res.code) {
                    wx.showLoading({
                        title: '加载中',
                        //duration: 500
                    });
                    utils.FetchRequest('/v1/api/wxLogin',
                        {
                            code: res.code,
                            srcId: that.data.code
                        })
                        .then((res) => {
                            wx.setStorageSync('userInfo', res.data.data);
                            wx.setStorageSync('token', res.data.data.token);
                            that.setData({
                                userInfo: res.data.data
                            });
                            if (res.data.data.register) {
                                that.setData({
                                    isShow: true
                                });
                                return
                            }
                            utils.FetchRequest('/v1/api/userInfo', {}, "get").then((res) => {
                                wx.hideLoading();
                                wx.setStorageSync('info', res.data.data);
                                that.setData({
                                    info: res.data.data
                                });
                                if (that.data.userInfo.register) {
                                    that.setData({
                                        isShow: true
                                    })
                                } else if (that.data.info.bankcardResult != 2) {
                                    wx.redirectTo({
                                        url: '/pages/bindCard/bindCard'
                                    })
                                } else if (that.data.info.idcardResult != 2) {
                                    wx.redirectTo({
                                        url: '/pages/authentication/authentication'
                                    })
                                } else {
                                    wx.switchTab({
                                        url: '/pages/index/index'
                                    })
                                }
                            }).catch((e) => {
                                wx.hideLoading();
                                that.setData({
                                    isShow: true
                                })
                            });
                        })
                        .catch((e) => {
                            wx.hideLoading();
                            that.setData({
                                isShow: true
                            })
                        })
                } else {
                    console.log(res.errMsg)
                }
            },
            fail: function () {
                wx.hideLoading();
                that.setData({
                    isShow: true
                });
                console.log("login---fail");
            },
            complete(e) {
                console.log("login---complete");
            }
        })
    },
    agreementUser: function () {
        wx.navigateTo({
            url: '/pages/USAgreement/USAgreement'
        })
    },
    bindGetUserInfo (e) {
        if (e.detail.errMsg == "getUserInfo:ok") {
            this.wxLogin();
        } else {
            wx.showToast({
                title: "请同意授权！",
                icon: 'none',
                duration: 2000
            })
        }

    },
    agreementPrivacy: function () {
        wx.navigateTo({
            url: '/pages/agreementPrivacy/agreementPrivacy'
        })
    },
    getPhoneNumber: function (e) {//点击获取手机号码按钮
        wx.checkSession({
            success: function () {
                var ency = e.detail.encryptedData;
                var iv = e.detail.iv;
                var userId = null;
                if (wx.getStorageSync('userInfo') != null) {
                    userId = wx.getStorageSync('userInfo').userId;
                }
                if (userId == null) {
                    wx.showToast({
                        title: "没有登录成功! ",
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }
                if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
                    wx.showToast({
                        title: "请同意授权！",
                        icon: 'none',
                        duration: 2000
                    })
                } else {//同意授权
                    utils.FetchRequest('/v1/api/wxRegister',
                        {
                            encryptedData: ency,
                            iv: iv,
                            userId: userId
                        }).then((res) => {
                        if (res.data.status == 200) {
                            wx.setStorageSync('userInfo', res.data.data);
                            wx.setStorageSync('token', res.data.data.token);
                            wx.redirectTo({
                                url: '/pages/bindCard/bindCard'
                            })
                        } else {
                            wx.showToast({
                                title: res.data.message,
                                icon: 'none',
                                duration: 3000
                            })
                        }
                    })
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        wx.hideHomeButton()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
})